var userIdArr = location.search.match(/id=(\d+)/)
    var token = location.search.match(/token=([^&]+)/)
    var c = document.querySelector('.c');
    if (userIdArr) {
        promiseAjax({
            url: "http://localhost:8888/cart/list",
            data: {
                id: userIdArr[1]
            },
            headers: {
                authorization: token[1]
            }
        }).then(res => {
            console.log(res);
            var { cart } = res;
            if (!cart.length) {
                var str = `
            <div class="jumbotron">
                <h1>购物车空空如也
                ！</h1>
                <p>心动不行动，赶快去列表页挑选商品吧！</p>
                <p><a class="btn btn-primary btn-lg" href="list.html?id=${userIdArr[1]}&token=${token[1]}" role="button">列表页</a></p>
            </div>
            `
                c.innerHTML = str;
                return;
            }
            var str = '';
            cart.forEach(item => {
                str += `
                <tr>
                    <td><input type="checkbox" name="selectOne" checked></td>
                    <td>
                        <img src="${item.img_small_logo}" widtd=80 height=80>
                    </td>
                    <td>
                        <p>${item.title.slice(0, 10)}</p>
                        <p>${item.category}</p>
                    </td>
                    <td>￥<span class="price">${item.price}</span>元</td>
                    <td>
                        <button class="reduce">-</button>
                        <input type="number" value="${item.cart_number}" name="number">
                        <button class="add">+</button>
                    </td>
                    <td>￥<span class="subtotal">${item.price * item.cart_number}</span>元</td>
                    <td data-stock="${item.goods_number}" data-id="${item.goods_id}"><button class="remove">删除</button></td>
                </tr>
            `
            })
            document.querySelector('.cart tbody').innerHTML = str
            select()
            handlerNumber()
            count()
            remove()
        })
    } else {
        alert("请先登录")
        location.href = "login.html"
    }
    // 删除购物车
    function remove() {
        var removes = document.querySelectorAll('.remove');
        for (var i = 0; i < removes.length; i++) {
            removes[i].onclick = function () {
                if (!confirm("你确定要删除吗？")) {
                    return false;
                }
                // 获取商品id
                var goodsid = this.parentElement.getAttribute('data-id')
                promiseAjax({
                    url: "http://localhost:8888/cart/remove",
                    headers: {
                        authorization: token[1]
                    },
                    data: {
                        id: userIdArr[1],
                        goodsId: goodsid
                    }
                }).then(res => {
                    console.log(res);
                    var tbody = this.parentElement.parentElement.parentElement
                    // 实现表格删除
                    this.parentElement.parentElement.parentElement.removeChild(this.parentElement.parentElement)
                    console.log(this.parentElement.parentElement.parentElement);
                    if (!tbody.children.length) {
                        var str = `
                            <div class="jumbotron">
                                <h1>购物车空空如也
                                ！</h1>
                                <p>心动不行动，赶快去列表页挑选商品吧！</p>
                                <p><a class="btn btn-primary btn-lg" href="list.html?id=${userIdArr[1]}&token=${token[1]}" role="button">列表页</a></p>
                            </div>
                        `
                        c.innerHTML = str;
                    }
                })

            }
        }
    }
    // 计算小计和总数量总价格
    function count() {
        var numbers = document.querySelectorAll('[name="number"]');
        var prices = document.querySelectorAll('.price');
        var subtotals = document.querySelectorAll('.subtotal');
        for (var i = 0; i < numbers.length; i++) {
            subtotals[i].innerText = ((prices[i].innerText - 0) * (numbers[i].value - 0)).toFixed(2)
        }
        // 计算总数量
        var n = 0;
        var p = 0
        var selectOne = document.querySelectorAll('[name="selectOne"]');
        // 转数组
        var arr = [].slice.call(selectOne)
        var brr = arr.filter(item => item.checked)
        brr.forEach((v, i) => {
            var num = v.parentElement.parentElement.querySelector('[name="number"]').value - 0;
            n += num

            var price = v.parentElement.parentElement.querySelector('.subtotal').innerText - 0
            p += price
        })
        document.querySelector('.totalNum').innerText = n;
        document.querySelector('.totalPrice').innerText = p.toFixed(2);
    }
    // 数量加和减
    function handlerNumber() {
        var reduces = document.querySelectorAll('.reduce');
        for (var i = 0; i < reduces.length; i++) {
            reduces[i].onclick = function () {
                var num = this.nextElementSibling.value - 0;
                num--;
                if (num <= 1) {
                    num = 1
                }
                this.nextElementSibling.value = num
                // 获取当前商品的id
                var goodsid = this.parentElement.parentElement.lastElementChild.getAttribute('data-id')
                editNumber(userIdArr, goodsid, num, token)
                count()
            }
        }
        var numbers = document.querySelectorAll('[name="number"]');
        for (var i = 0; i < numbers.length; i++) {
            numbers[i].oninput = function () {
                var goodsid = this.parentElement.parentElement.lastElementChild.getAttribute('data-id')
                var num = this.value;
                if (num <= 1) {
                    num = 1
                    this.value = num
                }
                // 获取库存
                var stock = this.parentElement.parentElement.lastElementChild.getAttribute('data-stock') - 0
                if (num > stock) {
                    num = stock
                    this.value = num
                }
                console.log(num);
                editNumber(userIdArr, goodsid, num, token)
                count()
            }
        }

        var adds = document.querySelectorAll('.add');
        for (var i = 0; i < adds.length; i++) {
            adds[i].onclick = function () {
                var num = this.previousElementSibling.value - 0;
                num++;
                // 获取库存
                var stock = this.parentElement.parentElement.lastElementChild.getAttribute('data-stock')
                if (num >= stock) {
                    num = stock
                }
                this.previousElementSibling.value = num
                // 获取当前商品的id
                var goodsid = this.parentElement.parentElement.lastElementChild.getAttribute('data-id')
                editNumber(userIdArr, goodsid, num, token)
                count()
            }
        }
    }

    // 修改数量
    function editNumber(userIdArr, goodsid, num, token) {
        promiseAjax({
            url: "http://localhost:8888/cart/number",
            data: {
                id: userIdArr[1],
                goodsId: goodsid,
                number: num
            },
            method: "post",
            headers: {
                authorization: token[1],
                "content-type": "application/x-www-form-urlencoded"
            }
        }).then(res => {
            console.log(res);
        })
    }
    // 单选全选
    function select() {
        // 全选
        var selectAll = document.querySelectorAll('[name="selectAll"]');
        var selectOne = document.querySelectorAll('[name="selectOne"]');
        for (var i = 0; i < selectAll.length; i++) {
            selectAll[i].onclick = function () {
                for (var j = 0; j < selectOne.length; j++) {
                    selectOne[j].checked = this.checked
                }
                for (var j = 0; j < selectAll.length; j++) {
                    selectAll[j].checked = this.checked
                }
                count()
            }
        }
        for (var i = 0; i < selectOne.length; i++) {
            selectOne[i].onclick = function () {
                var arr = [].slice.call(selectOne)
                var bool = arr.every(item => item.checked)
                for (var j = 0; j < selectAll.length; j++) {
                    selectAll[j].checked = bool
                }
                count()
            }
        }
    }